package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.allenliu.versionchecklib.callback.APKDownloadListener;
import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.DownloadBuilder;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.allenliu.versionchecklib.v2.callback.CustomDownloadingDialogListener;
import com.allenliu.versionchecklib.v2.callback.CustomInstallListener;
import com.allenliu.versionchecklib.v2.callback.CustomVersionDialogListener;
import com.example.myapplication.util.CommandExecution;
import com.example.myapplication.util.LogUtil;
import com.example.myapplication.util.SystemCtrlUtil;
import com.permissionx.guolindev.PermissionX;
import java.io.File;
import java.util.ArrayList;
public class InstallActivity extends AppCompatActivity {
    private BootReceiver bootReceiver;

    private String mApkName = "update.apk";

    private static Button btnDownload;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_install);

        registerReceiverBoot();

        TextView textView = findViewById(R.id.tv_version);
        textView.setText("版本号："+ BuildConfig.VERSION_NAME);

        btnDownload = findViewById(R.id.download);
        btnDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                downLoadApk();
            }
        });

        Button btn = findViewById(R.id.install);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isSu = CommandExecution.isSuEnable();
                if (isSu) {
                    LogUtil.i("有Root权限");
//                    CommandExecution.execCommand("pm uninstall " + InstallActivity.this.getPackageName(), true);

//                    File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                    File file = MyApplication.getContext().getFilesDir();
                    if (file.exists()) {
                        LogUtil.i("下载目录： "+file.getPath());
                        File apkfile = new File(file.getPath(), mApkName);
                        if (!apkfile.exists()) {
                            LogUtil.i("尚无APK文件");
                            return;
                        }
                        new Thread(){
                            @Override
                            public void run() {
                                CommandExecution.execCommand("pm install -r " + apkfile.getPath(), true, new CallBack());
                            }
                        }.start();
                    }
                } else  {
                    LogUtil.i("系统尚无Root权限");
                }
            }
        });
    }

    private static class CallBack implements CallBackResult {

        @Override
        public void result(String msg) {
            if (msg.equals("Success")) {
                String packageName = "com.example.myapplication";
                String cmd = "am start -n " + packageName + "/" + ".InstallActivity";
                CommandExecution.execCommand(cmd,true);
            }
        }
    }

    private void checkPermission(String cmd) {
        boolean isStorage = ContextCompat.checkSelfPermission(InstallActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED;
        boolean isAudio = ContextCompat.checkSelfPermission(InstallActivity.this, Manifest.permission.RECORD_AUDIO)
                == PackageManager.PERMISSION_GRANTED;
        if (isStorage || isAudio) {
            CommandExecution.execCommand(cmd, true, new CallBack());
        } else  {
            requestPermission(cmd);
        }
    }

    /**
     * 请求视频、音频、图片权限
     */
    private void requestPermission(String cmd) {
        ArrayList<String> requestList = new ArrayList<>();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            requestList.add(Manifest.permission.READ_MEDIA_IMAGES);
            requestList.add(Manifest.permission.READ_MEDIA_AUDIO);
            requestList.add(Manifest.permission.READ_MEDIA_VIDEO);
        } else {
            requestList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            requestList.add(Manifest.permission.RECORD_AUDIO);
        }
        PermissionX.init(this)
                .permissions(requestList)
                .onExplainRequestReason((scope, deniedList) -> {
                    scope.showRequestReasonDialog(deniedList, "PermissionX需要您同意以下权限才能正常使用", "Allow", "Deny");
                })
                .request((allGranted, grantedList, deniedList) -> {
                    if (allGranted) {
                        Toast.makeText(this, "所有申请的权限都已通过", Toast.LENGTH_SHORT).show();
                        CommandExecution.execCommand(cmd, true, new CallBack());
                    } else {
                        Toast.makeText(this, "您拒绝了如下权限：$deniedList", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    public void registerReceiverBoot() {
        if (bootReceiver==null) {
            bootReceiver = new  BootReceiver();
        } else {
            unregisterReceiver(bootReceiver);
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
        intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
        intentFilter.addDataScheme("package");

        registerReceiver(bootReceiver,intentFilter);
    }

    private void downLoadApk() {
        String downloadUrl = "https://amplify-spo2appflutter-test-105855-deployment.s3.ap-northeast-1.amazonaws.com/2.apk";
        DownloadBuilder downloadBuilder= AllenVersionChecker
                .getInstance()
                .downloadOnly(
                        UIData.create().setDownloadUrl(downloadUrl)
                );
        downloadBuilder.setApkName(mApkName);
        downloadBuilder.setCustomDownloadingDialogListener(new CustomDownloadingDialogListener() {
            @Override
            public Dialog getCustomDownloadingDialog(Context context, int i, UIData uiData) {
                LogUtil.i("getCustomDownloadingDialog");
                return null;
            }

            @Override
            public void updateUI(Dialog dialog, int i, UIData uiData) {
                LogUtil.i("updateUI");
                dialog.dismiss();
            }
        });
        downloadBuilder.setCustomVersionDialogListener(new CustomVersionDialogListener() {
            @Override
            public Dialog getCustomVersionDialog(Context context, UIData uiData) {
                return new Dialog(context);
            }
        });
        downloadBuilder.setShowDownloadingDialog(false);
//        downloadBuilder.setSilentDownload(true);
        downloadBuilder.setShowDownloadFailDialog(false);
        downloadBuilder.setDirectDownload(true);
        downloadBuilder.setShowNotification(false);
        downloadBuilder.setCustomDownloadInstallListener(new CustomInstallListener() {
            @Override
            public void install(Context context, Uri uri) {
                LogUtil.i("install");
            }
        });
//        downloadBuilder.setNotificationBuilder(
//                NotificationBuilder.create()
//                        .setRingtone(true)
//                        .setIcon(R.mipmap.appicon)
//                        .setTicker("正在下载")
//                        .setContentTitle(MyApplication.getContext().getString(R.string.app_name))
//                        .setContentText("正在下载资源文件...")
//        );
        downloadBuilder.setDownloadAPKPath(createDownLoadPath(MyApplication.getContext()));
        downloadBuilder.setApkDownloadListener(new APKDownloadListener() {
            @Override
            public void onDownloading(int progress) {
//                LogUtil.i("onDownloading 进度："+progress);
            }

            @Override
            public void onDownloadSuccess(File file) {
                LogUtil.i("onDownloading Success：" + file.getPath());
                new Thread() {
                    @Override
                    public void run() {
                        CommandExecution.execCommand("pm install -r " + file.getPath(), true, new CallBack());
                    }
                }.start();
            }

            @Override
            public void onDownloadFail() {
                LogUtil.i("onDownloading Fail");
            }
        });
        downloadBuilder.setRunOnForegroundService(true);
        downloadBuilder.executeMission(InstallActivity.this);
    }

    private String createDownLoadPath(Context context)  {
        String appCachePath = context.getFilesDir().getAbsolutePath();
        File file = new File(appCachePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        LogUtil.i("下载地址："+appCachePath);
        return appCachePath;
    }


    /**
     * 静默升级：这里是同步的，正式要考虑异步thread去做这个事情！！！
     * 1、检查系统是否有root权限
     * 2、检查APP是否有root权限
     * 3、确认安装包是否存在，并可读写
     * 4、root下安装apk
     * 5、root下通知开启apk
     * <p>
     * 注意：
     * 在当前的activity必要有个screenOrientation方向，否则的话runtime运行会把询问授予root权限的框给占用掉
     */
    private void sinlenceInstallApk(String apkPath, String apkName) {
        LogUtil.i("sinlenceInstallApk():-----------------");

        //1
        if (!SystemCtrlUtil.sysHasRootPerssion()) {
            LogUtil.e("系统尚无Root权限");
            Toast.makeText(this, "系统尚无Root权限", Toast.LENGTH_SHORT).show();
            return;
        }
        LogUtil.i("系统有Root权限");

        //2
//        if(!SystemCtrlUtil.appHasRootPerssion(this)){
//            LogUtil.e("APP尚无Root权限");
//            Toast.makeText(this,"APP尚无Root权限",Toast.LENGTH_SHORT).show();
//            return;
//        }
//        LogUtil.i("APP有Root权限");

        //3
        File apkfile = new File(apkPath, apkName);
        if (!apkfile.exists()) {
            LogUtil.e("尚无APK文件");
            return;
        }

        //4、静默安装
        if (SystemCtrlUtil.rootSlienceInstallApk(apkPath + "/" + apkName)) {
            LogUtil.d("静默安装成功");

            //5、执行此命令后：com.example.myapplication.BootReceiver 监听到Intent.ACTION_PACKAGE_REPLACED，然后自启动
            if (SystemCtrlUtil.rootStartApk("com.shortvideo.kjl.one", ".activity.ActivityStart")) {
                LogUtil.d("静默安装后启动APP成功");
            } else {
                LogUtil.e("静默安装后启动APP失败！！！");
                Toast.makeText(this, "静默安装后启动APP失败！！！", Toast.LENGTH_SHORT).show();
            }

        } else {
            LogUtil.e("静默安装失败！！！");
            Toast.makeText(this, "静默安装失败！！！", Toast.LENGTH_SHORT).show();
        }
    }
}